package com.ant.common.interceptor;

import com.ant.common.exceptions.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter(filterName = "ReqesFilter",
        urlPatterns = "/*",/*通配符（*）表示对所有的web资源进行拦截*/
        initParams = {
                @WebInitParam(name = "charset", value = "utf-8")/*这里可以放一些初始化的参数*/
        })
public class ReqesFilter implements Filter {

    private HttpServletRequest request;
    private String charset;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        charset = filterConfig.getInitParameter("charset");
        if (Objects.isNull(charset)) {
            charset = "utf-8";
        }
    }

    /**
     * 拦截/service/return_order/的请求
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String errorCode = "5001";
        try {
            servletRequest.setCharacterEncoding(charset);
            request = (HttpServletRequest) servletRequest;
            String requestURI = request.getRequestURI();
            request.setAttribute("isError", false);
            filterChain.doFilter(servletRequest, servletResponse);
        } catch (Exception e) {
            log.error("[ReqFilter] error : " + e.getMessage());
            request.setAttribute("isError", true);
            request.setAttribute("errorCode", errorCode);
            request.setAttribute("errorMsg", e.getMessage());
            throw new BusinessException(errorCode, e.getMessage());
        }
    }

    @Override
    public void destroy() {

    }
}
